package com.test.tm.service.impl;

import com.test.tm.mapper.TmMapper;
import com.test.tm.feign.FeignService;
import com.test.tm.service.TmService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalLock;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * tm业务逻辑方法
 */
@Slf4j
@Service
public class TmServiceImpl implements TmService {

    @Autowired
    private TmMapper tmMapper;
    @Autowired
    private FeignService feignService;

    AtomicInteger ai = new AtomicInteger(0);

    /**
     * 往本地插入记录
     * 再请求tcc服务插入一条记录
     *
     * @param params - name
     * @return String
     */
    @Override
    @GlobalTransactional(timeoutMills = 60000 * 2)
    @Transactional
    public String insertTcc(Map<String, String> params) {
        log.info("------------------> xid = " + RootContext.getXID());
        tmMapper.insert(params);
        feignService.insertTCC(params);
        if(ai.getAndIncrement()%5==0){
            throw new RuntimeException("tm: " + RootContext.getXID());
        }
        return "success";
    }

    @Override
    public String updateTcc(Map<String, String> params) {
        tmMapper.update(params);
        if(ai.getAndIncrement()%5==0){
            throw new RuntimeException("tm: " + RootContext.getXID());
        }
        return "success";
    }

    /**
     * 请求本地事务插入一条记录
     * 再请求at服务插入一条记录
     *
     * @param params - name
     * @return String
     */
    @Override
    @GlobalTransactional(timeoutMills = 60000 * 2)
    @Transactional
    public String insertAt(Map<String, String> params) {
        log.info("------------------> xid = " + RootContext.getXID());
        tmMapper.insert(params);
        feignService.insertAT(params);
        if(ai.getAndIncrement()%5==0){
            throw new RuntimeException("tm: " + RootContext.getXID());
        }
        return "success";
    }

    @Override
    @GlobalTransactional(timeoutMills = 60000 * 2)
    public String updateAt1(Map<String, String> params) {
        tmMapper.update(params);
        params.put("name", ai.getAndIncrement()+"");
        feignService.insertAT(params);
        return "success";
    }

    @Override
    @GlobalLock
    public String updateAt2(Map<String, String> params) {
        tmMapper.update(params);
        return "success";
    }

}
